package utils

import (
	"errors"
	"gogo/log"

	"go.mongodb.org/mongo-driver/bson"
)

func (c *GoGo_Utils_Class) BsonMarshalE(v interface{}) []byte {
	if v == nil {
		log.This().Error("v is nil")
		return nil
	}

	data, err := bson.Marshal(v)
	if err != nil {
		log.This().ErrorF("%v ===> %v", v, err)
		return nil
	}

	return data
}

func (c *GoGo_Utils_Class) BsonUnmarshalE(data []byte, v interface{}) error {
	if data == nil {
		log.This().Error("data is nil")
		return errors.New("data is nil")
	}

	if len(data) == 0 {
		log.This().Error("data len is 0")
		return errors.New("data len is 0")
	}

	if v == nil {
		log.This().Error("v is nil")
		return errors.New("v is nil")
	}

	if err := bson.Unmarshal(data, v); err != nil {
		log.This().ErrorF("%s... ===> %v", string(data[:100]), err)
		return err
	}
	return nil
}

func (c *GoGo_Utils_Class) BsonUnmarshalB(data []byte, v interface{}) bool {
	if err := c.BsonUnmarshalE(data, v); err == nil {
		return true
	}
	return false
}
